/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using Conversion = System.Qizx.Xdm.Conversion;
using System.Qizx.XQuery;
using Expression = System.Qizx.XQuery.Op.Expression;
namespace System.Qizx.XQuery.Dt
{
	
	public class BooleanType:AtomicType
	{
		public override string ShortName
		{
			get
			{
				return "boolean";
			}
			
		}
		
		public override int quickCode()
		{
			return QT_BOOL;
		}
		
		public override XQValue cast(XQItem value, EvalContext context)
		{
			XQItemType type = value.ItemType;
			
			switch (type.quickCode())
			{
				
				case XQType.QT_STRING: 
				case XQType.QT_UNTYPED: 
					string s = value.ValueAsString.Trim();
					if (s.Equals("true") || s.Equals("1"))
						return new SingleBoolean(true);
					if (s.Equals("false") || s.Equals("0"))
						return new SingleBoolean(false);
					throw new XQTypeException(Conversion.ERR_CAST, "cannot cast to xs:boolean: " + s);
				
				case XQType.QT_DEC: 
				case XQType.QT_INT: 
				case XQType.QT_FLOAT: 
				case XQType.QT_DOUBLE: 
				// extension
				case XQType.QT_BOOL: 
					return new SingleBoolean(value.ValueAsBoolean);
				
				
				default: 
					invalidCast(type);
					return null;
				
			}
		}
		
		public override XQValue convertFromObject(System.Object object_Renamed)
		{
			return new SingleBoolean(((System.Boolean) object_Renamed));
		}
		
		public override XQValue convertFromArray(System.Object object_Renamed)
		{
			bool[] array = (bool[]) object_Renamed;
			ArraySequence res = new ArraySequence(array.Length, null);
			for (int i = 0, asize = array.Length; i < asize; i++)
			{
				res.addItem(new SingleBoolean(array[i])); // a bit costly TODO
			}
			return res;
		}
		
		public override System.Object convertToObject(Expression expr, Focus focus, EvalContext context)
		{
			return expr.evalAsBoolean(focus, context);
		}
	}
}